package com.guangaiboen.attendance.core.dispatcher.utils;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.guangaiboen.attendance.core.dispatcher.exception.DispatcherException;

/**
 * XML工具类
 */
public class XMLUtils {

    private static XmlMapper mapper;

    static{
        mapper = new XmlMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
    }

    /**
     * bean 转 xml
     * @param bean
     * @return
     */
    public static String toXMLString(Object bean) {
        try {

            return mapper.writeValueAsString(bean);
        } catch (Exception e) {
            throw new DispatcherException(e);
        }
    }

    /**
     * xml转 bean
     * @param xmlBody xml文本
     * @param clazz 父类类型Class
     * @param types 子类范型
     * @param <T> 父类类型
     * @return
     */
    public static <T> T parseObject(String xmlBody, Class<T> clazz,Class<?> ... types) {
        try {
            JavaType type = mapper.getTypeFactory().constructParametricType(clazz, types);
            return mapper.readValue(xmlBody,type);
        } catch (Exception e) {
            throw new DispatcherException(e);
        }
    }
}
